package com.hwg.shiliupro.controller;

import com.hwg.shiliupro.annotation.Authority;
import com.hwg.shiliupro.dto.PageBean;
import com.hwg.shiliupro.dto.ScoreDto;
import com.hwg.shiliupro.dto.UserQueryDto;
import com.hwg.shiliupro.finals.Code;
import com.hwg.shiliupro.po.R;
import com.hwg.shiliupro.po.User;
import com.hwg.shiliupro.service.UserService;
import com.hwg.shiliupro.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页and条件查询
     *
     * @return {@link R}
     */
    @PostMapping("/selectByPageAndCondition")
    @Authority("user:selectByPageAndCondition")
    public R selectByPageAndCondition(@RequestBody UserQueryDto userQueryDto){
        log.info("分页查询前端条件为：{}",userQueryDto);
        PageBean<User> users = userService.selectByPageAndCondition(userQueryDto);
        return R.ok().code(Code.GET_OK).data(users);
    }

    /**
     * 新增用户
     *
     * @param user 用户
     * @return {@link R}
     */
    @PostMapping("/insert")
    @Authority("user:insert")
    public R insertUser(@RequestBody User user){
        log.info("新增用户数据为：{}",user);
        if(userService.insertUser(user)){
            return R.ok().code(Code.SAVE_OK);
        }
        return R.error().code(Code.SAVE_ERR).message("新增失败~");
    }

    /**
     * 删除用户通过id
     *
     * @param id id
     * @return {@link R}
     */
    @DeleteMapping("/{id}")
    @Authority("user:deleteById")
    public R deleteById(@PathVariable Integer id){
        if(userService.deleteById(id)){
            return R.ok().code(Code.DELETE_OK);
        }
        return R.error().code(Code.DELETE_ERR).message("删除失败~");
    }

    /**
     * 批量删除由ids
     *
     * @return {@link R}
     */
    @PostMapping("more")
    @Authority("user:deleteByIds")
    public R deleteByIds(@RequestBody int[] ids){
        log.info("批量删除传递的id数组为：{}",ids);
        for (int id : ids) {
            if(!userService.deleteById(id)){
                return R.error().code(Code.DELETE_ERR).message("删除失败~");
            }
        }
        return R.ok().code(Code.DELETE_OK);
    }

    /**
     * 更新用户
     *
     * @param user 用户
     * @return {@link R}
     */
    @PutMapping
    @Authority("user:updateByUser")
    public R updateUser(@RequestBody User user){
        if(userService.updateUser(user)){
            return R.ok().code(Code.UPDATE_OK);
        }
        return R.error().code(Code.UPDATE_ERR).message("修改失败~");
    }

    /**
     * 正常更改密码
     *
     * @param user 用户
     * @return {@link R}
     */
    @PutMapping("/updatePasswordNotForget")
    @Authority("user:updatePasswordNotForget")
    public R updatePasswordNotForget(@RequestBody User user){
        if(userService.updateUser(user)){
            return R.ok().code(Code.UPDATE_OK);
        }
        return R.error().code(Code.UPDATE_ERR).message("修改失败~");
    }

    /**
     * 忘记密码 发送邮件
     *
     * @param user 用户
     * @return {@link R}
     */
    @PostMapping("/sendMail")
    public R forgetPassword(@RequestBody User user){
        String mail = user.getMail();
        log.info("接收到的邮箱是：{}",mail);
        if(!mail.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,5}")){
            return R.error().code(Code.GET_ERR).message("邮箱格式错误~");
        }
        User u = userService.selectByMail(mail);
        if(u == null){
            return R.error().code(Code.GET_ERR).message("邮箱填写错误~");
        }
        //邮箱存在
        R r = userService.sendMail(u);
        return r;
    }

    /**
     * 更新密码通过邮件
     *
     * @param number      数量
     * @param protectCode 保护代码
     * @return {@link R}
     */
    @GetMapping("/updatePasswordByMail")
    public void updatePasswordByMail(String number, String protectCode, HttpServletResponse response) throws IOException {
        //重置密码为学号+uuid的后四位
        //执行修改密码  传参 protectCode 和 新密码
        String newPassword = number + protectCode.substring(28);
        boolean flag = userService.updatePasswordByProtectCode(protectCode, newPassword);
        log.info("是否重置密码成功:{}",flag);
        String message = flag == true ? "修改成功,请<a href='http://localhost:7070/#/login'>登录</a>" : "系统错误~";
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(message);
    }

    /**
     * 拉黑用户
     *  block 前端传输过来的 拉黑截至时间 2022-12-09T16:17
     * @param id    id
     * @param block 块
     * @return {@link R}
     */
    @PutMapping("/block/{id}")
    @Authority("user:blockUser")
    public R blockById(@PathVariable Integer id,@RequestBody String block){
        //block : 2022-12-09T16:17
        if(userService.blockById(id, block)){
            return R.ok().code(Code.UPDATE_OK);
        }
//        System.out.println(block);
        return R.error().code(Code.UPDATE_ERR).message("拉黑失败~");
    }


    @GetMapping("/score")
    @Authority("user:score")
    public R score(){
        List<ScoreDto> scoreDtos = userService.selectAllScore();
        log.info("组装后的积分榜数据：{}",scoreDtos);
        return R.ok().code(Code.GET_OK).data(scoreDtos);
    }

}
